package org.eenie.hookui.hook


import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.content.Intent
import android.view.View
import de.robv.android.xposed.*
import de.robv.android.xposed.callbacks.XC_LoadPackage
import org.eenie.hookui.ui.PluginMainActivity
import org.eenie.hookui.utils.ParasiticManager


class HookOsmoEntry : IXposedHookLoadPackage, IXposedHookZygoteInit {

    private val TARGET_PKG = "com.zft.osmo"

    private var plugin_path = ""
    private lateinit var clzLoader: ClassLoader


    override fun handleLoadPackage(lpparam: XC_LoadPackage.LoadPackageParam) {

        if (lpparam.packageName.equals(TARGET_PKG)) {
            XposedBridge.log("hook start " + lpparam.packageName)

            clzLoader = lpparam.classLoader


            XposedHelpers.findAndHookMethod(
                clzLoader.loadClass("com.zft.osmo.OsmoApp"),
                "onCreate",
                object : XC_MethodHook() {
                    override fun afterHookedMethod(param: MethodHookParam) {
                        XposedBridge.log("app start")
                        val app = param.thisObject as Application

                        ParasiticManager.initForStubActivity(app, plugin_path)

                    }
                })

            XposedHelpers.findAndHookMethod(clzLoader.loadClass("com.zft.osmo.ui.main.theads.me.MineFragment"), "initUI", View::class.java, object : XC_MethodHook(52) {
                override fun afterHookedMethod(param: MethodHookParam) {
                    val rootView = param.args[0] as View

                    val context = rootView.context
                    rootView.findViewById<View>(context.resources.getIdentifier("lay_about", "id", context.packageName))?.setOnClickListener {

                        context.startActivity(Intent(context, PluginMainActivity::class.java))
                    }


                }
            })


        }


    }


    fun isMainProcess(app: Context): Boolean {
        val am = app.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val pid = android.os.Process.myPid()
        val pkg = app.packageName
        am.runningAppProcesses.forEach {
            if (pid == it.pid && it.processName == pkg) {
                return true
            }
        }
        return false
    }

    override fun initZygote(startupParam: IXposedHookZygoteInit.StartupParam?) {
        plugin_path = startupParam?.modulePath ?: ""
        XposedBridge.log(plugin_path)
    }


}